package cn.hxzy.commonUser.service.impl;

import cn.hxzy.entity.userEntity.BankAccount;
import cn.hxzy.commonUser.mapper.BankAccountMapper;
import cn.hxzy.commonUser.service.BankAccountService;
import cn.hxzy.entity.userEntity.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ao.Li
 * @since 2023-06-23
 */
@Service
public class BankAccountServiceImpl extends ServiceImpl<BankAccountMapper, BankAccount> implements BankAccountService {

    @Autowired
    private BankAccountMapper bankAccountMapper;

    /**
     * 通过用户id查询用户密码是否正确，以及余额是否充足
     *
     * @param userId
     * @return
     */
    @Override
    public Boolean selectBankByUserId(String userId, int pwd, Double money) {
//        判断为空
        if (Objects.isNull(userId)) {
            return false;
        }

        //根据用户对象查询账户
        QueryWrapper<BankAccount> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        BankAccount bankAccount = bankAccountMapper.selectOne(wrapper);

//        判断密码
        if (bankAccount.getPaymentPassword() != pwd) {
            return false;
        }

        //获取用户余额
        double balance = bankAccount.getUserBalance().doubleValue();
        //判断用户余额不能小于用户需要支付的余额
        if (balance < money) {
            return false;
        }

        //计算余额
        BankAccount bank = new BankAccount();
        Double realBalance = balance - money;
        BigDecimal bigDecimal = BigDecimal.valueOf(realBalance);
        bank.setUserBalance(bigDecimal);
        //重新根据用户编号设置余额
        int flag = bankAccountMapper.update(bank, wrapper);
        if (flag > 0) return true;

        return false;
    }

    /**
     * 修改支付密码
     * @param userId
     * @param oldPwd
     * @param newPwd
     * @return
     */
    @Override
    public Boolean updatePayPwdById(String userId, int oldPwd, int newPwd) {
        UpdateWrapper<BankAccount> wrapper = new UpdateWrapper<>();
        wrapper.eq("user_id",userId);
        BankAccount bankAccount = bankAccountMapper.selectOne(wrapper);

        //判断输入的旧密码与数据库的旧密码是否相同
        if (bankAccount.getPaymentPassword() != oldPwd) {
            return false;
        }

        //设置新密码
        BankAccount bank = new BankAccount();
        bank.setPaymentPassword(newPwd);
        int i = bankAccountMapper.update(bank, wrapper);
        if (i > 0) {
            return true;
        }
        return false;
    }
}
